package com.dhcc.core.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.entity.User;

/**
 * 后台访问权限拦截器
 * 
 * @ClassName: BackendInterceptor
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:54:55
 */
public class BackendInterceptor implements HandlerInterceptor {

    private SysProperties sysProperties;

    public BackendInterceptor(SysProperties sysProperties) {
        this.sysProperties = sysProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        User user = ShiroKit.getUser();
        // 未登录不拦截
        if (CommonUtil.isEmpty(user)) {
            return true;
        } else {
            // 登出不拦截
            if (request.getRequestURI().equals(sysProperties.getBackendPath() + "/logout")) {
                return true;
            }
            // 判断为null不拦截
            if (CommonUtil.isEmpty(this.sysProperties.getBackendRoleNames())) {
                return true;
            }
            // 判断角色
            if (ShiroKit.hasAnyRoles(this.sysProperties.getBackendRoleNames())) {
                return true;
            }
            throw new BizException("没有访问后台的权限！", 401);
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
            ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            Object o, Exception e) throws Exception {

    }
}